package cn.xerllent.wxtp.handler;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.hutool.core.util.ObjectUtil;
import cn.xerllent.wxtp.entity.WxCorp;
import cn.xerllent.wxtp.entity.WxDepartment;
import cn.xerllent.wxtp.entity.WxDepartmentUser;
import cn.xerllent.wxtp.entity.WxTag;
import cn.xerllent.wxtp.entity.WxUser;
import cn.xerllent.wxtp.service.WxCorpService;
import cn.xerllent.wxtp.service.WxDepartmentService;
import cn.xerllent.wxtp.service.WxDepartmentUserService;
import cn.xerllent.wxtp.service.WxTagService;
import cn.xerllent.wxtp.service.WxUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.message.WxCpTpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

/**
 * 通讯录变更事件处理器.
 *
 */
@Component
public class ContactHandler extends AbstractHandler {

	private final WxCorpService wxCorpService;
	private final WxDepartmentService wxDepartmentService;
	private final WxDepartmentUserService wxDepartmentUserService;
	private final WxUserService wxUserService;
	private final WxTagService wxTagService;

	public ContactHandler(WxCorpService wxCorpService,WxDepartmentService wxDepartmentService,WxDepartmentUserService wxDepartmentUserService,WxUserService wxUserService,WxTagService wxTagService) {
		super();
		this.wxCorpService = wxCorpService;
		this.wxDepartmentService = wxDepartmentService;
		this.wxDepartmentUserService = wxDepartmentUserService;
		this.wxUserService = wxUserService;
		this.wxTagService = wxTagService;
	}


	@Override
	public WxCpXmlOutMessage handle(WxCpTpXmlMessage wxMessage, Map<String, Object> context, WxCpTpService wxCpTpService,
			WxSessionManager sessionManager) {
		String suiteId = wxCpTpService.getWxCpTpConfigStorage().getSuiteId();
		String corpId = wxMessage.getAuthCorpId(); // 授权企业id

		try {
			WxCorp wxCorp = wxCorpService.getOne(new LambdaQueryWrapper<WxCorp>().eq(WxCorp::getCorpId, corpId).eq(WxCorp::getSuiteId, suiteId));
			//使用企业三方api时，先调用此方法:如果没有企业accesstoken则通过api获取并缓存到storage
			wxCpTpService.getCorpToken(wxCorp.getCorpId(), wxCorp.getPermanentCode(),false);

			String changeType = wxMessage.getChangeType();
			if(changeType.equals(WxCpConsts.ContactChangeType.CREATE_PARTY)){
				Integer departmentId = Integer.parseInt(wxMessage.getId());
				Integer parentId = Integer.parseInt(wxMessage.getParentId());
				Integer od = wxMessage.getOrder();

				WxDepartment d = new WxDepartment().setCorpId(corpId).setDepartmentId(departmentId).setParentId(parentId).setOd(od);
				wxDepartmentService.save(d);

			}else if(changeType.equals(WxCpConsts.ContactChangeType.UPDATE_PARTY)){
				Integer departmentId = Integer.parseInt(wxMessage.getId());
				Integer parentId = Integer.parseInt(wxMessage.getParentId());
				Integer od = wxMessage.getOrder();
				WxDepartment d= wxDepartmentService.getOne(new LambdaQueryWrapper<WxDepartment>().eq(WxDepartment::getCorpId, corpId).eq(WxDepartment::getDepartmentId, departmentId));
				if(d==null) {
					d = new WxDepartment().setCorpId(corpId).setDepartmentId(departmentId).setParentId(parentId);
				}else {
					d.setParentId(parentId);
				}
				if(od!=null) {d.setOd(od);}

				wxDepartmentService.saveOrUpdate(d);
			}else if(changeType.equals(WxCpConsts.ContactChangeType.DELETE_PARTY)){
				Integer departmentId = Integer.parseInt(wxMessage.getId());
				wxDepartmentService.remove(new LambdaQueryWrapper<WxDepartment>().eq(WxDepartment::getCorpId, corpId).eq(WxDepartment::getDepartmentId, departmentId));

				//删除关联数据
				wxDepartmentUserService.remove(new LambdaQueryWrapper<WxDepartmentUser>().eq(WxDepartmentUser::getCorpId, corpId).eq(WxDepartmentUser::getDepartmentId, departmentId));

			}else if(changeType.equals(WxCpConsts.ContactChangeType.CREATE_USER)){
				WxUser u = new WxUser();
				u.setCorpId(corpId);
				if(wxMessage.getMainDepartment()!=null) u.setMainDepartmentId(wxMessage.getMainDepartment());
				u.setUserId(wxMessage.getUserID());
				String openUserId = (String) wxMessage.getAllFieldsMap().get("OpenUserID");
				if(ObjectUtil.isNotEmpty(openUserId)) u.setOpenUserid(openUserId);
				if(ObjectUtil.isNotEmpty(wxMessage.getName())) u.setName(wxMessage.getName());
				if(ObjectUtil.isNotEmpty(wxMessage.getAlias())) u.setAlias(wxMessage.getAlias());
				if(ObjectUtil.isNotEmpty(wxMessage.getAvatar())) u.setAvatar(wxMessage.getAvatar());
				if(wxMessage.getGender()!=null) u.setGender(wxMessage.getGender().toString());
				u.setStatus(Integer.parseInt(wxMessage.getStatus()));
				u.setTelephone(wxMessage.getMobile());
				wxUserService.save(u);

				//部门用户关系处理
				for(int i=0;i<wxMessage.getDepartment().length;i++) {
					Integer dId = wxMessage.getDepartment()[i];
					WxDepartmentUser du = new WxDepartmentUser();
					du.setCorpId(corpId);
					du.setDepartmentId(dId);
					du.setUserId(wxMessage.getUserID());
					try {du.setIs_leader(wxMessage.getDepartment()[i]>0);} catch (Exception e) {}

					try {wxDepartmentUserService.save(du);} catch (Exception e) {}
				}

			}else if(changeType.equals(WxCpConsts.ContactChangeType.UPDATE_USER)){
				//1获取保存user
				String userId = wxMessage.getUserID();
				WxUser u = wxUserService.getOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getCorpId, corpId).eq(WxUser::getUserId, userId));
				if(u==null) {u = new WxUser();}
				u.setCorpId(corpId);
				u.setUserId(wxMessage.getUserID());
				String newUserId = (String)wxMessage.getAllFieldsMap().get("NewUserID");
				if(newUserId!=null) u.setUserId(newUserId);
				if(wxMessage.getMainDepartment()!=null) u.setMainDepartmentId(wxMessage.getMainDepartment());
				String openUserId = (String) wxMessage.getAllFieldsMap().get("OpenUserID");
				if(ObjectUtil.isNotEmpty(openUserId)) u.setOpenUserid(openUserId);
				if(ObjectUtil.isNotEmpty(wxMessage.getName())) u.setName(wxMessage.getName());
				if(ObjectUtil.isNotEmpty(wxMessage.getAlias())) u.setAlias(wxMessage.getAlias());
				if(ObjectUtil.isNotEmpty(wxMessage.getAvatar())) u.setAvatar(wxMessage.getAvatar());
				if(wxMessage.getGender()!=null) u.setGender(wxMessage.getGender().toString());
				if(wxMessage.getStatus()!=null) u.setStatus(Integer.parseInt(wxMessage.getStatus()));
				if(wxMessage.getMobile()!=null) u.setTelephone(wxMessage.getMobile());
				wxUserService.saveOrUpdate(u);

				//部门用户关系处理，
				//2.1 先删除原来的
				wxDepartmentUserService.remove(new LambdaQueryWrapper<WxDepartmentUser>().eq(WxDepartmentUser::getCorpId, corpId).eq(WxDepartmentUser::getUserId, userId));
				//2.2 再加新的
				for(int i=0;i<wxMessage.getDepartment().length;i++) {
					Integer dId = wxMessage.getDepartment()[i];
					WxDepartmentUser du = new WxDepartmentUser();
					du.setCorpId(corpId);
					du.setDepartmentId(dId);
					du.setUserId(userId);
					try {du.setIs_leader(wxMessage.getDepartment()[i]>0);} catch (Exception e) {}

					try {wxDepartmentUserService.save(du);} catch (Exception e) {}
				}

			}else if(changeType.equals(WxCpConsts.ContactChangeType.DELETE_USER)){
				String userId = wxMessage.getUserID();
				//1.删除user
				wxUserService.remove(new LambdaQueryWrapper<WxUser>().eq(WxUser::getCorpId, corpId).eq(WxUser::getUserId, userId));
				//2 部门用户关系
				wxDepartmentUserService.remove(new LambdaQueryWrapper<WxDepartmentUser>().eq(WxDepartmentUser::getCorpId, corpId).eq(WxDepartmentUser::getUserId, userId));

			}else if(changeType.equals(WxCpConsts.ContactChangeType.UPDATE_TAG)){
				//查找本地存储tag
				Integer tagId = wxMessage.getTagId();
				WxTag wxTag = wxTagService.getOne(new LambdaQueryWrapper<WxTag>().eq(WxTag::getCorpId, corpId).eq(WxTag::getTagid, tagId));
				if(wxTag==null) { //数据不对应，则重新同步一下
				    wxTagService.syncTags(wxCpTpService, wxCorp);
				    wxTag = wxTagService.getOne(new LambdaQueryWrapper<WxTag>().eq(WxTag::getCorpId, corpId).eq(WxTag::getTagid, tagId));
				}
				//初始化参数
				if(wxTag.getUserlist()==null) wxTag.setUserlist(new HashSet<String>());
				if(wxTag.getPartylist()==null) wxTag.setPartylist(new HashSet<Integer>());

				//更改变化
				if(ObjectUtil.isNotEmpty(wxMessage.getAddUserItems())) {
					wxTag.getUserlist().addAll(Arrays.stream(wxMessage.getAddUserItems()).collect(Collectors.toSet()));
				}
				if(ObjectUtil.isNotEmpty(wxMessage.getDelUserItems())) {
					wxTag.getUserlist().removeAll(Arrays.stream(wxMessage.getDelUserItems()).collect(Collectors.toSet()));
				}

				if(ObjectUtil.isNotEmpty(wxMessage.getAddPartyItems())) {
					wxTag.getPartylist().addAll(Arrays.stream(wxMessage.getAddPartyItems()).collect(Collectors.toSet()));
				}
				if(ObjectUtil.isNotEmpty(wxMessage.getDelPartyItems())) {
					wxTag.getPartylist().removeAll(Arrays.stream(wxMessage.getDelPartyItems()).collect(Collectors.toSet()));
				}

				//地存储tag
				wxTagService.saveOrUpdate(wxTag);
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
		}

		return null;
	}

}
